package cn.dengta.context.web;

import java.util.concurrent.TimeUnit;

import cn.dengta.common.security.CryptoSuite;
import cn.dengta.common.web.Client;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Getter
@Setter
@ConfigurationProperties(prefix = CryptoSuiteContext.PREFIX)
public class CryptoSuiteContext implements InitializingBean {

	static final String PREFIX = "webapp.context.encrypt";

	boolean enabled = true;
	String version = "1.0.0";
	CryptoSuite.CryptoSuiteAttrs android;
	CryptoSuite.CryptoSuiteAttrs ios;
	long allowMaxDelay = TimeUnit.MINUTES.toMillis(10);

	@Setter(AccessLevel.NONE)
	CryptoSuite androidSuite;
	@Setter(AccessLevel.NONE)
	CryptoSuite iOSSuite;

	@Override
	public void afterPropertiesSet() throws Exception {
		if (isEnabled()) {
			this.androidSuite = new CryptoSuite().checkAndInit(android);
			this.iOSSuite = new CryptoSuite().checkAndInit(ios);
		}
	}

	public CryptoSuite getCryptoSuite(Client client) {
		if (client.isAPP()) {
			return client == Client.APP_ANDROID ? androidSuite : iOSSuite;
		}
		return null;
	}

}
